// Popup脚本
document.addEventListener('DOMContentLoaded', () => {
  const toggle = document.getElementById('enableToggle');
  const tokenInput = document.getElementById('tokenInput');
  const saveTokenBtn = document.getElementById('saveToken');
  const storageKey = 'gitcode-tree-enabled';
  const tokenKey = 'gitcode-tree-token';

  // 加载当前状态
  chrome.storage.local.get([storageKey, tokenKey], (result) => {
    const isEnabled = result[storageKey] !== false; // 默认启用
    toggle.classList.toggle('active', isEnabled);
    
    // 加载token（显示为*号）
    if (result[tokenKey]) {
      tokenInput.value = result[tokenKey].replace(/./g, '*');
      tokenInput.dataset.hasValue = 'true';
    }
  });

  // 切换开关
  toggle.addEventListener('click', () => {
    const isActive = toggle.classList.contains('active');
    const newState = !isActive;
    
    toggle.classList.toggle('active', newState);
    chrome.storage.local.set({ [storageKey]: newState });

    // 通知content script
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'toggle',
          enabled: newState
        });
      }
    });
  });

  // Token输入框焦点事件
  tokenInput.addEventListener('focus', () => {
    if (tokenInput.dataset.hasValue === 'true') {
      tokenInput.value = '';
      tokenInput.dataset.hasValue = 'false';
    }
  });

  // 保存Token
  saveTokenBtn.addEventListener('click', () => {
    const token = tokenInput.value.trim();
    if (token) {
      chrome.storage.local.set({ [tokenKey]: token }, () => {
        tokenInput.value = token.replace(/./g, '*');
        tokenInput.dataset.hasValue = 'true';
        saveTokenBtn.textContent = '已保存';
        saveTokenBtn.style.background = '#28a745';
        setTimeout(() => {
          saveTokenBtn.textContent = '保存';
          saveTokenBtn.style.background = '#0366d6';
        }, 2000);
        
        // 通知content script刷新
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]) {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: 'refresh'
            });
          }
        });
      });
    }
  });

  // 支持回车保存
  tokenInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      saveTokenBtn.click();
    }
  });
});

